﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using SimpleSpreadsheet.Core;
using SimpleSpreadsheet.Core.Expressions;

namespace SimpleSpreadsheet.Functions
{
    /// <summary>
    /// Evaluates the maximum of decimal arguments
    /// </summary>
    [Export(typeof (IFunction))]
    public class Max : IFunction
    {
        #region IFunction Members

        public string Name
        {
            get { return "MAX"; }
        }

        public decimal Evaluate(IList<BaseExpression> arguments, ExpressionVisitor expressionVisitor)
        {
            if (arguments.Count() == 0)
                throw new ArgumentException("Empty arguments list");

            IEnumerator<BaseExpression> enumerator = arguments.GetEnumerator();
            enumerator.MoveNext();
            decimal result = Convert.ToDecimal(expressionVisitor.Evaluate(enumerator.Current));
            while (enumerator.MoveNext())
                result = Math.Max(result, Convert.ToDecimal(expressionVisitor.Evaluate(enumerator.Current)));

            return result;
        }

        #endregion
    }
}